<template>
  <div>
    <a-card>
      <!-- 搜索部分 -->
      <a-row type="flex" justify="end" class="search-module">
        <a-input-search
          v-model:value="searchValue"
          placeholder="搜索活动名称"
          class="search-module_input"
          @search="confirmGetInviteList"
        ></a-input-search>
        <a-button type="primary" @click="showInvite">创建邀请码活动</a-button>
      </a-row>
      <!-- 表格部分 -->
      <a-table
        :columns="columns"
        :loading="data.loading"
        :data-source="data.dataSource"
        :pagination="false"
        rowKey="inviteId"
      >
        <template #handler="{ record }">
          <div v-if="record.status !== 2 && record.status !== 3">
            <a @click="getDetail(record)">查看</a>
            <a class="line">|</a>
            <a @click="toCodeLibrary(record.inviteId)">码库</a>
          </div>
          <div v-else>
            <a @click="editInviteActive(record)">编辑</a>
            <a class="line">|</a>
            <a @click="toCodeLibrary(record.inviteId)">码库</a>
            <a class="line">|</a>
            <a-popconfirm
              title="确定使当前活动失效？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirmEditInviteLose(record.inviteId)"
            >
              <a>立即失效</a>
            </a-popconfirm>
          </div>
        </template>
        <template #timer="{ record }">
          <div>起：{{ record.startTime }}</div>
          <div>止：{{ record.endTime }}</div>
        </template>
        <template #codeCount="{ record }">
          <div>{{ record.notHaveCode }}/{{ record.haveCode }}</div>
        </template>
      </a-table>
      <a-row style="margin-top: 20px" type="flex" justify="end">
        <a-pagination
          show-quick-jumper
          showSizeChanger
          v-model:pageSize="pagination.pageSize"
          v-model:current="pagination.current"
          :total="pagination.total"
          :showTotal="() => `共 ${pagination.total} 条数据`"
          @change="getList"
          @showSizeChange="getList"
        />
      </a-row>
    </a-card>
    <!-- 抽屉 -->
    <a-drawer
      placement="right"
      :title="inviteDrawer.title"
      :visible="inviteDrawer.visible"
      :width="600"
      @close="closeInviteDrawer"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item label="活动名称" name="inviteName">
          <a-input
            v-model:value="formState.inviteName"
            placeholder="请输入活动名称"
            :disabled="formDisabled"
          />
        </a-form-item>
        <a-form-item label="兑换内容" name="content" class="required">
          <a-checkbox v-model:checked="formState.type" :disabled="true || !!formState.status">
            服务版本
          </a-checkbox>
          <a-row type="flex" align="middle">
            <a-select
              :disabled="true || !!formState.status"
              v-model:value="formState.edition"
              style="width: 32%; margin-right: 5px"
            >
              <a-select-option value="standard">标准版</a-select-option>
            </a-select>
            <a-input-number
              :disabled="formDisabled || !!formState.status"
              v-model:value="formState.year"
              placeholder="邀请码数量"
              style="width: 32%; margin-right: 5px"
              :min="0"
              :formatter="limitNumber"
            ></a-input-number>
            <span>年</span>
          </a-row>
          <div>
            每家店铺可用
            <a-input-number
              :disabled="formDisabled || !!formState.status"
              v-model:value="formState.number"
              placeholder="邀请码数量"
              style="width: 170px"
              :min="0"
              :formatter="limitNumber"
            ></a-input-number>
            个
          </div>
        </a-form-item>
        <a-form-item label="活动时间" name="timer">
          <a-range-picker
            :disabled="formDisabled"
            :show-time="{
              format: 'HH:mm',
              hideDisabledOptions: true,
              defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('00:00:00', 'HH:mm:ss')],
            }"
            :placeholder="['生效时间', '失效时间']"
            style="width: 325px"
            :format="dateFormatList"
            v-model:value="formState.timer"
          />
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-textarea
            :disabled="formDisabled"
            v-model:value="formState.remark"
            placeholder="输入备注信息"
            allow-clear
          />
        </a-form-item>
      </a-form>
      <div
        :style="{
          position: 'absolute',
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e8e8e8',
          padding: '10px 16px',
          textAlign: 'right',
          left: 0,
          background: '#fff',
          borderRadius: '0 0 4px 4px',
        }"
      >
        <a-button style="margin-right: 8px" @click="closeInviteDrawer">取消</a-button>
        <a-button type="primary" :loading="loading" :disabled="loading" @click="onSubmit">
          确定
        </a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script>
import { ref, defineComponent, reactive, toRaw } from 'vue';
import moment from 'moment';
import { columns } from './utils';
import { useRouter } from 'vue-router';
import { limitNumber } from '@/utils/helper';
import {
  apiAddInviteActive,
  apiGetInviteList,
  apiEditInvite,
  apiEditInviteLose,
} from '@/api/marketSetting/inviteAcitve';
import { message } from 'ant-design-vue';
import { parseTime } from '@/utils';
const dateFormatList = ['YYYY/MM/DD HH:mm:ss', 'YYYY/MM/DD HH:mm:ss'];
const transList = list => {
  const editionMap = {
    standard: '标准版本',
    professional: '专业版本',
    advanced: '高级版本',
    trial: '试用版本',
  };
  return list.map(item => {
    item.startTime = parseTime(item.startTime);
    item.endTime = parseTime(item.endTime);
    item.editionStr = `${editionMap[item.edition]}： ${item.year}年`;
    return item;
  });
};
export default defineComponent({
  name: '',
  setup() {
    // 列表数据
    const data = reactive({
      loading: false,
      dataSource: [],
    });

    // 搜索活动名称
    const searchValue = ref('');

    // 分页数据
    const pagination = reactive({
      total: 0,
      current: 1,
      pageSize: 10,
    });

    /**
     * 获取列表
     **/
    const getList = async () => {
      data.loading = true;
      try {
        const { pageInfo } = await apiGetInviteList({
          pageNum: pagination.current,
          pageSize: pagination.pageSize,
          inviteName: searchValue.value,
        });
        data.dataSource = transList(pageInfo.list);
        pagination.total = pageInfo.total;
        // const res = await apiGetInviteList({
        //   pageNum: pagination.current,
        //   pageSize: pagination.pageSize,
        //   inviteName: searchValue.value,
        // });
        // data.dataSource = transList(res.data.rows);
        // pagination.total = res.data.total;
      } catch (error) {
        console.dir(error);
      } finally {
        data.loading = false;
      }
    };
    getList();

    // 表单显示
    const inviteDrawer = reactive({
      visible: false,
      title: '创建邀请码活动',
    });

    /**
     * 展示邀请码活动表单
     **/
    const showInvite = () => {
      formDisabled.value = false;
      inviteDrawer.visible = true;
      inviteDrawer.title = '创建邀请码活动';
    };

    /**
     * 关闭填邀请码活动表单
     **/
    const closeInviteDrawer = () => {
      inviteDrawer.visible = false;
      resetForm();
    };

    // 表单组件
    const formRef = ref();

    // 路由
    const router = useRouter();

    // 表单默认值
    const formState = reactive({
      inviteName: '',

      number: 0,
      timer: undefined,
      remark: '',
      type: true,
      edition: 'standard',
      year: 1,
      status: '',
    });

    // 表单校验规则
    const rules = {
      inviteName: [
        {
          required: true,
          message: '活动名称不能为空',
          trigger: 'blur',
        },
        {
          min: 1,
          max: 30,
          message: '活动名称不能超过30字',
        },
      ],
      content: [
        {
          validator: () => {
            if (!formState.type) {
              return Promise.reject('服务版本不能为空');
            }
            if (!formState.edition) {
              return Promise.reject('版本不能为空');
            }
            if (!formState.year) {
              return Promise.reject('时间不能为空');
            }
            //   return Promise.reject('时间单位不能为空');
            // }
            if (!formState.number) {
              return Promise.reject('邀请数量不能为空');
            }
            return Promise.resolve();
          },
          type: 'boolean',
        },
      ],
      timer: [
        {
          required: true,
          message: '请输入活动时间',
          trigger: 'change',
          type: 'array',
        },
      ],
    };

    /**
     * 获取列表数据
     **/
    const confirmGetInviteList = () => {
      pagination.current = 1;
      getList();
    };

    /**
     * 提交表单
     **/
    const onSubmit = () => {
      formRef.value
        .validate()
        .then(() => {
          formState.endTime = formState.timer[1]._d.getTime();
          formState.startTime = formState.timer[0]._d.getTime();
          formState.inviteId ? confirmEditInvite() : confirmAddInvite();
        })
        .catch(err => {
          console.log(err);
        });
    };

    /**
     * 确认添加邀请活动
     **/
    const confirmAddInvite = async () => {
      const { inviteName, remark, edition, year, startTime, endTime, number, type } = toRaw(
        formState,
      );
      const typeMap = type === true ? 1 : 0;
      try {
        loading.value = true;
        await apiAddInviteActive({
          inviteName,
          remark,
          edition,
          year,
          startTime,
          endTime,
          number,
          type: typeMap,
        });
        message.success('新增成功');
        closeInviteDrawer();
        getList();
      } finally {
        loading.value = false;
      }
    };

    // 提交请求加载中
    const loading = ref(false);

    /**
     * 确认编辑邀请活动
     **/
    const confirmEditInvite = async () => {
      const {
        inviteName,
        remark,
        edition,
        year,
        startTime,
        endTime,
        number,
        type,
        inviteId,
      } = toRaw(formState);
      const typeMap = type === true ? 1 : 0;
      try {
        loading.value = true;
        await apiEditInvite({
          inviteId,
          inviteName,
          remark,
          edition,
          year,
          startTime,
          endTime,
          number,
          type: typeMap,
        });
        message.success('编辑成功');
        closeInviteDrawer();
        getList();
      } finally {
        loading.value = false;
      }
    };

    /**
     * 重置表单
     **/
    const resetForm = () => {
      formRef.value.resetFields();
      formState.inviteName = '';
      formState.number = 0;
      formState.timer = undefined;
      formState.remark = '';
      formState.type = true;
      formState.edition = 'standard';
      formState.year = 1;
      formState.status = '';
      formState.inviteId = '';
    };

    /**
     * 弹出编辑邀请码抽屉
     **/
    const editInviteActive = form => {
      const {
        inviteId,
        inviteName,
        remark,
        edition,
        year,
        startTime,
        endTime,
        number,
        type,
        status,
      } = form;
      const dateFormat = 'YYYY/MM/DD';
      formState.inviteName = inviteName;
      formState.type = type === 1;
      formState.timer = [moment(startTime, dateFormat), moment(endTime, dateFormat)];
      formState.remark = remark;
      formState.edition = edition;
      formState.year = year;
      formState.inviteId = inviteId;
      formState.number = number;
      formState.status = status;
      inviteDrawer.visible = true;
      formDisabled.value = false;
    };

    /**
     * 跳转码库页面
     **/
    const toCodeLibrary = inviteId => {
      router.push({
        name: 'codeLibrary',
        params: {
          inviteId,
        },
      });
    };

    // 表单禁用
    const formDisabled = ref(true);
    const getDetail = form => {
      formDisabled.value = true;
      inviteDrawer.visible = true;
      const {
        inviteId,
        inviteName,
        remark,
        edition,
        year,
        startTime,
        endTime,
        number,
        type,
      } = form;
      const dateFormat = 'YYYY/MM/DD';
      formState.inviteName = inviteName;
      formState.type = type === 1;
      formState.timer = [moment(startTime, dateFormat), moment(endTime, dateFormat)];
      formState.remark = remark;
      formState.edition = edition;
      formState.year = year;
      formState.inviteId = inviteId;
      formState.number = number;
    };

    /**
     * 邀请活动失效
     **/
    const confirmEditInviteLose = inviteId => {
      apiEditInviteLose({ inviteId }).then(() => {
        getList();
        message.success('活动已失效');
      });
    };

    return {
      columns,
      data,
      searchValue,
      showInvite,
      inviteDrawer,
      closeInviteDrawer,
      formRef,
      editInviteActive,
      labelCol: {
        span: 4,
      },
      wrapperCol: {
        span: 14,
      },
      other: '',
      formState,
      rules,
      onSubmit,
      resetForm,
      toCodeLibrary,
      confirmGetInviteList,
      formDisabled,
      getDetail,
      dateFormatList,
      confirmEditInviteLose,
      pagination,
      getList,
      loading,
      limitNumber,
      moment,
    };
  },
});
</script>
<style lang="less" scoped>
.line {
  margin: 0 10px;
}
.search-module {
  margin-bottom: 20px;
  &_input {
    width: 207px;
    margin-right: 20px;
  }
}
.required {
  position: relative;
  &&::after {
    position: absolute;
    top: 12px;
    left: 10px;
    color: #ff4d4f;
    font-size: 14px;
    content: '*';
  }
}
</style>
